import { createRouter, createWebHistory } from 'vue-router'
import HomeView from "@/views/HomeView.vue";
import { ElMessage } from 'element-plus';
import { PageConstant, UserConstant } from '@/common/Constant';


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: '主页',
      component: HomeView,
      meta: {
        requiresAuth: false,
        title: '主页'
      }
    },
    {
      path: "/login",
      name: "登录",
      component: () => import("@/views/LoginView.vue"),
      meta: {
        requiresAuth: false,
        title: '登录'
      }
    },
    {
      path: "/profile",
      name: "个人信息",
      component: () => import("@/views/ProfileView.vue"),
      meta: {
        requiresAuth: true,
        title: '个人信息'
      },
      children: [
        {
          path: 'edit',
          name: '修改资料',
          component: () => import("@/components/user/ProfileEdit.vue"),
          meta: {
            requiresAuth: true,
            title: '修改资料'
          }
        }
      ]
    },
    {
      path: "/baguwen",
      name: "八股面试",
      component: () => import("@/views/BaguwenView.vue"),
      meta: {
        requiresAuth: true,
        title: '八股面试'
      },
      children: [
        {
          path: 'topic/:id',
          name: '题目合集',
          component: () => import("@/views/SubjectCollectionView.vue"),
          meta: {
            requiresAuth: true,
            title: '题目合集'
          }
        }
      ]
    },
    {
      path: "/onlinejudge",
      name: "OJ判题",
      component: () => import("@/views/OnlineJudgeView.vue"),
      meta: {
        requiresAuth: true,
        title: 'OJ判题'
      }
    },
    {
      path: "/ojsubmit/:id",
      name: "OJ解题",
      component: () => import("@/views/OJSubmitView.vue"),
      meta: {
        requiresAuth: true,
        title: 'OJ解题'
      }
    },
    {
      path: "/ojsubmit/add",
      name: "Oj新增题目",
      component: () => import("@/views/OJAddSubjectView.vue"),
      meta: {
        requiresAuth: true,
        title: 'Oj新增题目'
      }
    },
    {
      path: '/baguwen/detail/:id', // 子路由路径，最终完整路径为 /baguwen/topic/:id
      name: '题目详情',
      component: () => import('@/views/ProblemDetailView.vue'),
      meta: {
        requiresAuth: true,
        title: '题目详情'
      }
    },
    {
      path: '/baguwen/label/:id', // 子路由路径，最终完整路径为 /baguwen/topic/:id
      name: '标签-八股文',
      component: () => import('@/views/LabelProblemsView.vue'),
      meta: {
        requiresAuth: true,
        title: '标签-八股文'
      }
    },
    {
      path: '/baguwen/add', // 子路由路径，最终完整路径为 /baguwen/topic/:id
      name: '新增题目',
      component: () => import("@/views/AddBgwSubject.vue"),
      meta: {
        requiresAuth: true,
        title: '新增题目'
      }
    },
    // 404页面
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import("@/views/NotFoundView.vue"),
      meta: {
        requiresAuth: false,
        title: '404'
      }
    }
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title as string || '开发者探索';

  // 获取token
  const token = localStorage.getItem(UserConstant.tokenValue)
  const tokenName = localStorage.getItem(UserConstant.tokenName)

  // 如果已登录且要去登录页，直接跳转到首页
  if (token && tokenName && to.path === PageConstant.LoginPage) {
    ElMessage.info('您已登录，已为您跳转到首页')
    return next(PageConstant.HomePage)
  }

  // 如果页面需要登录且未登录，跳转到登录页
  if (to.meta.requiresAuth && (!token || !tokenName)) {
    ElMessage.warning('请先登录')
    return next({
      path: PageConstant.LoginPage,
      query: { redirect: to.fullPath } // 记录原本要去的路径
    });
  }
  // 其他情况正常放行
  next()
})

// 路由错误处理
router.onError((error) => {
  console.log(error);
  ElMessage.error('页面加载失败，请刷新重试');
})


export default router;
